package com.qidian.buy.order.interceptors;

import com.qidian.buy.util.QdConstant;
import com.qidian.buy.util.Tools;
import com.qidian.buy.util.pojo.QdResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

/**
 * Author: 戴着假发的程序员
 * Date: 2024-05-17 10:35
 * company: 起点编程
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private WebClient.Builder builder;
    @Value("${SSO_SERVICE_NAME}") // 在配置文件中添加配置  buy-sso
    private String ssoServiceName;

    // 拦截器的前置处理，可以拦截请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从request的header中获取token
        String token = request.getHeader("token");
        if(StringUtils.isNoneBlank(token)){// token存在
            // 校验token的有效性
            QdResult result = builder.build().get().uri("http://" + ssoServiceName + "/user/checkLogin?token=" + token)
                    .retrieve().bodyToMono(QdResult.class).block();
            if (result.getCode() == 200){
                // 获取用户的id
                LinkedHashMap data = (LinkedHashMap) result.getData();
                Object userId = data.get("userId");
                // 将用户的id放入request的作用域中
                request.setAttribute("userId",userId);
                // 放行
                return true;
            }
        }
        // 给客户端响应一个未登录状态  状态码为401
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(Tools.object2json(QdResult.error(QdConstant.RESPONSE_STATUS_UNAUTHORIZED,"未登录")));
        return false;// 拦截
    }
}
